import React, { useEffect, useRef, useState } from "react";
import { indexOf, map, once } from "underscore";
import Alymodel from "../../mysql_interface/model";
import {
  asyncgetvideoInfo,
  asyncselectWhitepoint,
  jilurizhi,
  post,
} from "../api/api";
import { delayed, videoDimensions } from "../utils";

type P = {
  lid: number;
  question: Alymodel.Ivideoquestion[];
  scratchheight?: number;
  scratchwidth?: number;
  value2?: string | number;
  course: Alymodel.IMcourse;
  getuser: Alymodel.IMuser;
};

type S = {
  videoList: [];
  player: any;
  playingVideo: any;
  videoLoading: boolean;
  multipleChoice: any;
  logtime: number;
  isuselogtime: boolean;
};

interface IAVideoMeta {
  VideoId: string;
  Title: string;
  Duration: number;
  CoverURL: string;
  Status: string;
}

interface IvideoList {
  RequestId: string;
  VideoMeta: IAVideoMeta;
  PlayAuth: string;
}




const AlyplayerComponent: React.FunctionComponent<P> = (p) => {
  const playertel = useRef<HTMLDivElement>(null);
  const playerTemp = useRef<HTMLDivElement>(null);
  const [openWT, setopenWT] = useState<number | null>(null);
  const [videoList, setvideoList] = useState<IvideoList>();
  const [whites, setwhites] = useState<Alymodel.Iwhitepoint[]>([]);
  const [dangqian, setdangqian] = useState(0);
  const [iswhites, setiswhites] = useState(false);
  const [videoLoading, setvideoLoading] = useState(false);
  const [logtime, setlogtime] = useState(Date.now());
  const [isuselogtime, setisuselogtime] = useState(false);
  const [divstyle, setdivstyle] = useState<React.CSSProperties>();
  const [read1, setread1] = useState(false);
  const [teltime777, setteltime777] = useState(0);
  window.onresize = () => {
    start();
  };

  function watchvideo(p: P, time: number) {
    const proportion = Math.floor(time / window.player.getDuration() * 100)
    if (proportion) {
      post('/studycode/v1/user/createdwatchvideo', {
        courseid: p.course.ID,
        time,
        proportion
      })
    }
  }

  async function start() {
    const v = document.querySelectorAll<HTMLVideoElement>("#video")[0];
    if (v) {
      let { width, height } = videoDimensions(v);
      if (width < 25) {
        await delayed(300);
      }
      width = videoDimensions(v).width;
      height = videoDimensions(v).height;
      let a = v.offsetHeight;
      let b = (a - height) / 2;
      setdivstyle({
        width: `${width}px`,
        height: `${height}px`,
        margin: "20px auto",
        top: `${b}px`,
      });
    }
  }

  useEffect(() => {

    asyncselectWhitepoint({ lid: p.lid });
    asyncgetvideoInfo({ lid: p.lid }).then((e: any) => {
      setvideoList(e);
    });
    ready();
  }, [p.lid]);

  useEffect(() => {
    window.player = undefined;
    asyncselectWhitepoint({ lid: p.lid });
    asyncgetvideoInfo({ lid: p.lid }).then((e: any) => {
      setvideoList(e);
    });
    ready();
    window.addEventListener('beforeunload', (event) => {
      let isuselogtime = false
      setisuselogtime(e => {
        isuselogtime = e
        return e
      })
      let logtime = Date.now()
      setlogtime(e => {
        logtime = e
        return e
      })
      if (isuselogtime) {
        watchvideo(p, Math.floor((Date.now() - logtime) / 1000))
      }
    });
    return () => {
      let isuselogtime = false
      setisuselogtime(e => {
        isuselogtime = e
        return e
      })
      let logtime = Date.now()
      setlogtime(e => {
        logtime = e
        return e
      })
      if (p.course && isuselogtime) {
        const arr: any = [];
        arr[0] = ["type", "video"];
        arr[1] = ["isdestroy", true];
        arr[2] = ["courseid", p.course.ID];
        arr[3] = ["coursename", p.course.name];
        arr[4] = ["watchtime", Date.now() - logtime];
        jilurizhi(arr);
        watchvideo(p, Math.floor((Date.now() - logtime) / 1000))
      }
      document.removeEventListener("keydown", playing, false);
      window.onresize = () => { };
      window.player?.dispose();
      window.player = undefined
      window.addEventListener('beforeunload', () => { });
    };
  }, []);


  useEffect(() => {
    if (videoList) {
      ended()
      if (window.player != null) {
        window.player.dispose();
      }
      createDemoPlayer(
        videoList.VideoMeta.VideoId,
        videoList.VideoMeta.CoverURL,
        videoList.PlayAuth
      );
      setvideoLoading(false);
    }
  }, [videoList]);

  function getwhite() {
    setiswhites(true);
    const arr = [];
    //定位快速搭建的位置
    for (let v of whites) {
      arr.push({
        offset: v.starttime,
        text: v.miaoshu,
      });
    }
    return arr;
  }

  async function createDemoPlayer(
    vid: string,
    cover: any,
    playauth: any
  ) {
    if (document.getElementById("player-con") === null) {
      let playerDomWrap = playerTemp.current;
      let playerDom = document.createElement("div");
      playerDom.setAttribute("id", "player-con");
      playerDomWrap?.appendChild(playerDom);
      //视频下方添加小div
      let bar = document.createElement("div");
      bar.setAttribute("id", "barcontrol");
      playerDom.appendChild(bar);
      setread1(true);
    }
    const progressMarkers = getwhite();
    let height =
      (p.scratchheight && p.scratchheight - 30) ||
      (document.getElementById("playerparent") as any).offsetWidth * 0.52 - 20;
    height = height > 850 ? 850 : height;
    let props = {
      id: "player-con",
      width: "100%",
      height: height + "px",
      autoplay: false,
      language: "zh-cn",
      preload: false,
      isLive: false,
      progressMarkers: progressMarkers,
      cover: cover,
      playauth: playauth,
      vid: vid,
      encryptType: 1,
      controlBarVisibility: "always",
      playsinline: true,
      useH5Prism: true,
      enableSystemMenu: true,
      keyShortCuts: true,
      defaultDefinition: 'HD',
    };

    const Aliplayer = window.Aliplayer;
    window.player = new Aliplayer(props);

    window.player.on("timeupdate", timeupdate);
    window.player.on("completeSeek", completeSeek);
    window.player.on("ended", ended);
    window.player.on("play", telplay);
    window.player.on("ready", _ready);
    window.player.on("pause", pause);
    window.player.on("playing", () => {
      setisuselogtime(true);

    });
    await delayed(100);
    let videoclicl = document.getElementsByTagName("video")[0];
    videoclicl.addEventListener("click", videoplayer, false);
  }

  /**
   * 暂停
   */
  function pause() {
    let isuselogtime = false
    setisuselogtime(e => {
      isuselogtime = e
      return e
    })
    let logtime = Date.now()
    setlogtime(e => {
      logtime = e
      return e
    })
    if (p.course && isuselogtime) {
      const arr: any = [];
      arr[0] = ["type", "video"];
      arr[1] = ["isended", true];
      arr[2] = ["courseid", p.course.ID];
      arr[3] = ["coursename", p.course.name];
      arr[4] = ["watchtime", Date.now() - logtime];
      jilurizhi(arr);
      watchvideo(p, Math.floor((Date.now() - logtime) / 1000))
    }
    setisuselogtime(false);
  }

  function _ready() {
    if (p.course) {
      const arr: any = [];
      arr.push(["type", "video"]);
      arr.push(["isready", true]);
      arr.push(["courseid", p.course.ID]);
      arr.push(["coursename", p.course.name]);
      jilurizhi(arr);
    }
  }
  const oncetelplay = once(_telplay);
  const telplay = () => {
    setlogtime(Date.now());
    setisuselogtime(true);
    oncetelplay()
  }

  function _telplay() {
    const text = p.getuser.userid + "正在观看";
    if (teltime777) return;
    let l = 1;
    let r = 1;
    const _teltime777 = window.setInterval(() => {
      const playerparent =
        document.querySelector<HTMLDivElement>("#player-con");
      const data = playerparent?.querySelector<HTMLDivElement>("#player-tel");
      if (!data && playertel.current) {
        playerparent?.appendChild(playertel.current);
      }
      const tel = document.querySelector<HTMLDivElement>("#player-tel");
      if (tel) {
        const left = parseInt(tel?.style.left || "0") + l;
        const top = parseInt(tel?.style.top || "0") + r;
        tel.style.left = left + "px";
        tel.style.color = "#fff";
        tel.style.position = "absolute";
        tel.style.zIndex = "999";
        tel.style.opacity = "0.6";
        tel.style.filter = "alpha(opacity=60)";
        tel.style.width = "200px";
        tel.style.textShadow = "0 0 0.2em #000";
        tel.style.height = "20px";
        tel.style.display = "block";
        tel.innerHTML = text;
        tel.style.top = top + "px";
        if (playerparent && left > playerparent.offsetWidth - 200) {
          l = -1;
        }
        if (left < 0) {
          l = 1;
        }
        if (playerparent && top > playerparent?.offsetHeight) {
          r = -1;
        }
        if (top < 0) {
          r = 1;
        }
      }
    }, 60);
    setteltime777(_teltime777);
  }

  function timeupdate() {
    if (p.question.length) {
      // 获取当前视频时间
      let currentTime = Math.ceil(window.player.getCurrentTime());
      let arr = [];
      for (let v of p.question) {
        arr.push(v.time);
      }
      // 判断是否在暂停时间内
      let index = indexOf(arr, currentTime);
      if (index != -1) {
        setopenWT(currentTime);
        setdangqian(index);
      }
    }
  }

  function ended() {
    if (p.course && isuselogtime) {
      const arr: any = [];
      arr[0] = ["type", "video"];
      arr[1] = ["isended", true];
      arr[2] = ["courseid", p.course.ID];
      arr[3] = ["coursename", p.course.name];
      arr[4] = ["watchtime", Date.now() - logtime];
      jilurizhi(arr);
      watchvideo(p, Math.floor((Date.now() - logtime) / 1000))
    }
    setopenWT(null);
    setisuselogtime(false);
  }

  function completeSeek() {
    setopenWT(null);
  }

  function ready() {
    document.addEventListener("keydown", playing, false);
  }

  function videoplayer() {
    if (window.player?.getStatus() === "playing") {
      window.player?.pause();
    }
    if (window.player?.getStatus() === "pause") {
      window.player?.play();
    }
    if (window.player?.getStatus() === "init") {
      window.player?.play();
    }
  }

  function playing(e: KeyboardEvent) {
    if (e.keyCode === 32) {
      videoplayer();
    } else if (e.keyCode === 39) {
      let currentTime = Math.ceil(window.player?.getCurrentTime());
      window.player?.seek((currentTime += 3));
    } else if (e.keyCode === 37) {
      let currentTime = Math.ceil(window.player?.getCurrentTime());
      window.player?.seek((currentTime -= 3));
    }
  }

  return (
    <div
      ref={playerTemp}
      className="player-olympic"
      style={{ height: read1 ? "auto" : "calc(100vh - 100px)" }}
      id="playerparent"
    >
      <div ref={playertel} style={divstyle} id="player-tel"></div>
    </div>
  );
};

export default AlyplayerComponent;
